import Immutable from 'seamless-immutable'
import { createSlice } from '@reduxjs/toolkit'
import { AnyAction } from 'redux'
import createRequestTypes from '@UTILS/reduxHelper'
import fetchDemo from '../thunk/demo'

const DEMO = createRequestTypes('DEMO')

const INITIAL_STATE = Immutable({
  data: 0 as number,
})

const demoSlice = createSlice({
  name: 'demo',
  initialState: INITIAL_STATE,
  reducers: {
    increment: (state, action: AnyAction) => {
      console.log(action.payload)
      return {
        ...state,
        data: state.data + 1,
      }
    },
    [DEMO.SUCCESS]: (state, action: AnyAction) => {
      console.log(action.payload)
      return {
        ...state,
        data: state.data + 1,
      }
    },
  },
  extraReducers: (builder) => {
    builder.addCase(fetchDemo.pending, (state, action) => {
      console.log(state)
      console.log(action)
    })
    builder.addCase(fetchDemo.rejected, (state, action) => {
      // todo yc 需要统一的错误处理函数
      console.log(state)
      console.log(action)
    })
    builder.addCase(fetchDemo.fulfilled, (state, action) => {
      console.log(state)
      console.log(action)
    })
  },
})

const { actions } = demoSlice
export { actions, DEMO }

export default demoSlice.reducer
